import { treeData } from "@/type";
import * as Antd from "antd";
import React, { ReactNode } from "react";

const returnElement: ({
  element,
  props,
  children,
}: treeData.treeDataType) => ReactNode = (domStyle: treeData.treeDataType) => {
  const { element, props = {}, children, text = "", key } = domStyle;
  try {
    if (element === "Page") {
      return returnChildren(children);
    }
    if (element === "text") {
      return domStyle.text;
    }
    if (children?.length === 0 && text) {
      return React.createElement(
        // @ts-expect-error 该值由用户拖拽决定，该值只会是组件名称
        Antd[element],
        { ...props, "data-key": key, key: key },
        text
      );
    }
    if (!children) return;

    return React.createElement(
      // @ts-expect-error 该值由用户拖拽决定，该值只会是组件名称
      Antd[element],
      { ...props, "data-key": key, key: key },
      ...returnChildren(children)
    );
  } catch (error) {
    console.log(error);
  }
};

const returnChildren = (arr: treeData.treeDataType["children"]) => {
  return arr.map((item) => {
    if (typeof item === "string") {
      return item;
    }
    return returnElement(item);
  });
};
export default returnElement;
